package com.syt.cellphone.information.base

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.*
import androidx.annotation.CallSuper
import androidx.appcompat.view.SupportMenuInflater
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.Fragment
import com.syt.cellphone.information.utils.applyTint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlin.coroutines.CoroutineContext

/**
 *  @author: syt
 *  创建时间: 2020/8/19 17:56
 *  @功能   基础fragment
 *  @version v1.0
 */
abstract class BaseFragment(layoutId: Int) : Fragment(layoutId), CoroutineScope {

    lateinit var job: Job
    // coroutineScope 的实现
    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job
    var supportToolbar: Toolbar ?= null
        private set
    val menuInflater: MenuInflater
        @SuppressLint("RestrictedApi")
        get() = SupportMenuInflater(requireContext())

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        job = Job()
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        onFragmentCreated(view, savedInstanceState)
        observeLiveBus()
    }

    /**
     * fragment建立后执行的操作 ——> Activity.onCreate 之后
     */
    abstract fun onFragmentCreated(view: View, savedInstanceState: Bundle?)

    // 子类继承后,重写这个方法,必须调用父类的super方法
    @CallSuper
    override fun onDestroy() {
        super.onDestroy()
        // 当Activity销毁时，取消该Scope管理的Job
        // 这样在该Scope内创建的子Coroutine都会被自动取消
        job.cancel()
    }

    /**
     * 设置工具栏
     */
    fun setSupportToolbar(toolbar: Toolbar) {
        supportToolbar = toolbar
        supportToolbar?.let {
            it.menu.apply {
                onCompatCreateOptionsMenu(this)
                applyTint(requireContext())
            }
            it.setOnMenuItemClickListener {item ->
                onCompatOptionsItemSelected(item)
                true
            }
        }
    }

    /**
     * liveBus处理
     */
    open fun observeLiveBus() {

    }

    /**
     * 在toolbar创建菜单
     */
    open fun onCompatCreateOptionsMenu(menu: Menu) {

    }

    /**
     * 设置菜单的选择界面
     */
    open fun onCompatOptionsItemSelected(item: MenuItem) {

    }

}